<template>
  <div id="article">
    <div class="nav">
      <Nav/>
    </div>
    <div class="col">
      <button @click="shou">收藏</button>
      <p>{{cang}}</p>
    </div>
    <div class="textSpring">
      <h1>{{view.title}}</h1>
      <p>作者：{{view.author}}</p>
      <hr>
      <div v-html="htmlContent"></div>
    </div>
  </div>
</template>

<script setup>
import { inject, onMounted, ref, computed, watch } from 'vue';
import MarkdownIt from 'markdown-it';
import Nav from '@/views/Layout/nav.vue';
import axios from 'axios';
import { useRoute } from 'vue-router';

const customAxios = axios.create({
  baseURL: 'http://localhost:8888',  // 基础 URL
  timeout: 5000  // 超时时间，单位为毫秒
});
customAxios.defaults.transformResponse = [];
const view = ref([]);

const route = useRoute();
const articleId = route.params.articleId;
console.log('获取到的文章ID为：', articleId);

function safeJsonParse(jsonStr) {
  const regex = /"(\w+)":([^,}]+)/g;
  let match;
  let result = '';
  let index = 0;
  while ((match = regex.exec(jsonStr))!== null) {
    const key = match[1];
    let value = match[2];
    if (key === 'id' && /^\d+$/.test(value)) {
      const numValue = Number(value);
      if (numValue > Number.MAX_SAFE_INTEGER) {
        value = `"${value}"`;
      }
    }
    result += jsonStr.slice(index, match.index) + `"${key}":${value}`;
    index = regex.lastIndex;
  }
  result += jsonStr.slice(index);
  return JSON.parse(result);
}


const getPostArticleView = async () => {
  try {
    const res = await customAxios.post('/articles/view/'+articleId);
    console.log(res);
    const parsedData = safeJsonParse(res.data);
    if (parsedData && parsedData.data) {
      view.value = parsedData.data;
    } else {
      console.error('解析后的数据中没有 data 属性');
    }
    // 直接在这里更新 htmlContent
    if (view.value && view.value.body && view.value.body.content) {
      const md = new MarkdownIt();
      htmlContent.value = md.render(view.value.body.content);
    }
  } catch (error) {
    console.error('请求文章详情数据失败:', error);
  }
};


onMounted(() => {
  getPostArticleView();
});


const cang = ref("未收藏");

const shou = () =>{
  if(cang.value == "未收藏"){
    cang.value = "已收藏";
  } else {
    cang.value = "未收藏";
  }
};

const htmlContent = ref('');

</script>

<style scoped>
#article{
  padding: 20px;
  padding-top: 60px;
  background-color: #d1bfbf;
  min-height: 600px;
}

.col{
  position: fixed;
  /* display: flex; // 横向展示*/
  left: 10px;
  top: 100px;
  width: 50px;
  height: 300px;
  /* border: 1px solid black;  */
  align-items: center;
  /* justify-content: space-around; */
  z-index: 999; /* 设置一个较高的 z-index 值，确保导航栏在其他元素之上 */
}

.textSpring{
  padding: 30px;
  margin: 0 auto;
  /* border: 1px solid black; */
  border-radius: 5px;
  width: 70%;
  background-color: rgb(250, 236, 241);
}
</style>